package com.zhan.signalling.connect.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.zhan.signalling.commons.Constants;
import com.zhan.signalling.message.AccoutType;
import com.zhan.signalling.message.Result;
import com.zhan.signalling.mock.Mock;

public class ZhanConnectListener implements ConnectListener {
	
	private static Logger log = LoggerFactory.getLogger(ZhanConnectListener.class);
	
	public void onConnect(SocketIOClient client) {
		Integer status = Constants.SUCCESS;
		String content = null;
		try {
			Integer type = null;
			if(client.getHandshakeData().getUrlParams().get("type") == null) {
				content = "请设置正确的参数　type";
				status = Constants.FAILED;
			}else {
				type = Integer.valueOf(client.getHandshakeData().getUrlParams().get("type").get(0));
				AccoutType accoutType = AccoutType.getInstance(type);
				log.info("sessionId:" + client.getSessionId() + ",type:" + type);
				switch (accoutType) {
				case ADMIN:
					String username = client.getHandshakeData().getUrlParams().get("username").get(0);
					String password = client.getHandshakeData().getUrlParams().get("password").get(0);
					if(Mock.username.equalsIgnoreCase(username) && Mock.password.equalsIgnoreCase(password)) {
						content = "connect success";
						client.set(Constants.USER_TYPE, type);
					}else {
						content = "connect failed";
						status = Constants.FAILED;
					}
					break;
				case MANAGER:
				case PARTICIPANT:
				case GUEST:
					String token = client.getHandshakeData().getUrlParams().get("token").get(0);
					String user = client.getHandshakeData().getUrlParams().get("user").get(0);
					//验证连接　TODO
					//AccoutLoginCheck.login(token, user);
					JSONObject accout = JSONObject.parseObject(user);
					client.set(Constants.USER_KEY, accout); 
					client.set(Constants.USER_TOKEN, token);
					content = "connect success";
					log.info("sessionId:" + client.getSessionId() + ",token:" + token);
					client.set(Constants.USER_TYPE, type);
					break;
				default:
					content = "请设置正确的参数　type";
					status = Constants.FAILED;
					break;
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			content = "连接异常，请查看参数";
			status = Constants.FAILED;
		}
		if(status == Constants.FAILED) {
			client.disconnect();
		}
		log.info(JSONObject.toJSONString(new Result(content,status)));
	}

}
